document.addEventListener('DOMContentLoaded', function() {
    // 获取URL参数
    const urlParams = new URLSearchParams(window.location.search);
    const orderId = urlParams.get('orderId');

    if (orderId) {
        // 加载订单详情页
        loadOrderDetail(orderId);
    } else {
        // 加载订单列表页
        loadOrderList();
    }
    // 绑定筛选按钮事件
    document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            const status = this.dataset.status;
            loadOrderList(status === 'all' ? null : status);
        });
    });
});
function formatImagePath(imagePath) {
    if (!imagePath) return '/static/no-image.png';

    // 如果路径已经是完整URL（如http开头），直接返回
    if (imagePath.startsWith('http')) {
        return imagePath;
    }

    // 统一处理为 /static/upload/ 开头的路径
    const cleanPath = imagePath
        .replace(/^\.\//, '')          // 去掉 ./ 前缀
        .replace(/^\/?upload\//, '')   // 去掉 upload/ 前缀
        .replace(/^\/?static\//, '');  // 去掉 static/ 前缀

    return `/static/upload/${cleanPath}`;
}
function loadOrderList(status = null) {
    const userId = 1; // 实际项目中应从登录信息获取
    let url = `http://localhost:8080/api/orders?userId=${userId}`;

    fetch(url)
        .then(response => response.json())
        .then(orders => {
            const orderListEl = document.getElementById('orderList');
            orderListEl.innerHTML = '';

            const filteredOrders = status ?
                orders.filter(order => order.status == status) :
                orders;

            if (filteredOrders.length === 0) {
                // 根据状态显示不同的提示信息
                let statusText = '';
                switch(status) {
                    case '0': statusText = '待支付'; break;
                    case '1': statusText = '已支付'; break;
                    case '2': statusText = '已发货'; break;
                    case '3': statusText = '已完成'; break;
                    default: statusText = '';
                }

                const noOrdersMsg = document.createElement('div');
                noOrdersMsg.className = 'no-orders';
                noOrdersMsg.innerHTML = `
                    <div class="empty-state">
                        <p>${statusText ? `暂无${statusText}的订单` : '暂无订单'}</p>
                        <a href="/products.html" class="btn btn-primary">去逛逛</a>
                    </div>
                `;
                orderListEl.appendChild(noOrdersMsg);
                return;
            }

            filteredOrders.forEach(order => {
                const items = order.orderItems || [];
                const address = order.address || {};

                const orderCard = document.createElement('div');
                orderCard.className = 'order-card';

                let statusText = '';
                switch(order.status) {
                    case 0: statusText = '待支付'; break;
                    case 1: statusText = '已支付'; break;
                    case 2: statusText = '已发货'; break;
                    case 3: statusText = '已完成'; break;
                }
                orderCard.innerHTML = `
                    <div class="order-header">
                        <span>订单号: ${order.orderNo}</span>
                        <span>状态: ${statusText}</span>
                        <span>金额: ${order.paymentAmount}元</span>
                    </div>
                    <div class="order-items">
                        ${items.length > 0 ? items.map(item => {
                    const imageUrl = formatImagePath(item.productImage);
                    return `
                                <div class="order-item">
                                    <img src="${imageUrl}" alt="${item.productName}" 
                                         onerror="this.src='/static/no-image.png'">
                                    <div>
                                        <p>${item.productName}</p>
                                        <p>${item.productPrice}元 × ${item.quantity}</p>
                                    </div>
                                </div>
                            `;
                }).join('') : '<p class="no-items">暂无商品</p>'}
                    </div>
                    <div class="order-footer">
                        <a href="order-detail.html?orderId=${order.id}" class="btn btn-primary">查看详情</a>
                    </div>
                `;
                orderListEl.appendChild(orderCard);
            });
        })
        .catch(error => {
            console.error('Error loading orders:', error);
            document.getElementById('orderList').innerHTML =
                '<p class="error">加载订单失败，请稍后重试</p>';
        });
}

function loadOrderDetail(orderId) {
    fetch(`http://localhost:8080/api/orders/${orderId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(order => {
            if (!order) {
                window.location.href = 'order-list.html';
                return;
            }

            // 填充订单基本信息
            document.getElementById('orderNo').textContent = order.orderNo || '--';

            // 处理订单状态
            let statusText = '';
            switch(order.status) {
                case 0:
                    statusText = '待支付';
                    document.getElementById('payBtn').style.display = 'block';
                    break;
                case 1: statusText = '已支付'; break;
                case 2:
                    statusText = '已发货';
                    document.getElementById('confirmBtn').style.display = 'block';
                    break;
                case 3: statusText = '已完成'; break;
                default: statusText = '未知状态';
            }
            document.getElementById('orderStatus').textContent = statusText;

            // 处理时间信息
            const createTime = order.paymentTime || new Date().toISOString();
            document.getElementById('createTime').textContent = new Date(createTime).toLocaleString();
            document.getElementById('paymentTime').textContent = order.paymentTime ? new Date(order.paymentTime).toLocaleString() : '--';
            document.getElementById('shippingTime').textContent = order.shippingTime ? new Date(order.shippingTime).toLocaleString() : '--';
            document.getElementById('totalAmount').textContent = order.paymentAmount || '0';
            if (order.status === 3 && order.completeTime) {
                document.getElementById('completeTimeRow').style.display = 'block';
                document.getElementById('completeTime').textContent = new Date(order.completeTime).toLocaleString();
            } else {
                document.getElementById('completeTimeRow').style.display = 'none';
            }

            // 处理收货信息
            const address = order.address || {};
            document.getElementById('receiverName').textContent = address.name || '--';
            document.getElementById('receiverPhone').textContent = address.phone || '--';
            document.getElementById('receiverAddress').textContent =
                [address.province, address.city, address.district, address.addr]
                    .filter(Boolean).join(' ') || '--';

            // 处理订单备注
            if (order.note) {
                document.getElementById('noteRow').style.display = 'block';
                document.getElementById('note').textContent = order.note;
            } else {
                document.getElementById('noteRow').style.display = 'none';
            }

            // 处理物流信息
            if (order.shippingCompany && order.shippingNo) {
                document.getElementById('shippingDetail').style.display = 'block';
                document.getElementById('shippingCompany').textContent = order.shippingCompany || '--';
                document.getElementById('shippingNo').textContent = order.shippingNo || '--';
            } else {
                document.getElementById('shippingDetail').style.display = 'none';
            }

            // 填充商品列表
            const itemListEl = document.getElementById('itemList');
            itemListEl.innerHTML = '';

            (order.orderItems || []).forEach(item => {
                const imageUrl = formatImagePath(item.productImage);
                const row = document.createElement('tr');
                row.innerHTML = `
                     <td>
                        <div class="order-item">
                            <img src="${imageUrl}" alt="${item.productName}"
                                 onerror="this.src='/static/no-image.png'">
                            <span>${item.productName || '--'}</span>
                        </div>
                    </td>
                    <td>${item.productPrice || '0'}元</td>
                    <td>${item.quantity || '0'}</td>
                    <td>${item.totalPrice || '0'}元</td>
                `;
                itemListEl.appendChild(row);
            });
            // 绑定支付按钮事件
            const payBtn = document.getElementById('payBtn');
            if (payBtn) {
                payBtn.addEventListener('click', function() {
                    window.location.href = `payment.html?orderId=${order.id}`;
                });
            }

            // 绑定确认收货按钮事件
            const confirmBtn = document.getElementById('confirmBtn');
            if (confirmBtn) {
                confirmBtn.addEventListener('click', function() {
                    if (confirm('确认收到商品了吗？')) {
                        fetch(`http://localhost:8080/api/orders/${order.id}/status`, {
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                            },
                            body: `status=3`
                        })
                            .then(response => {
                                if (response.ok) {
                                    alert('确认收货成功！');
                                    window.location.reload();
                                } else {
                                    alert('操作失败，请重试');
                                }
                            })
                            .catch(error => console.error('Error:', error));
                    }
                });
            }
        })
        .catch(error => {
            console.error('Error loading order detail:', error);
            alert('加载订单详情失败，请稍后重试');
            window.location.href = 'order-list.html';
        });
}